from selenium.common.exceptions import NoSuchElementException, NoAlertPresentException
from selenium import webdriver
import time
import smtplib
import pyautogui as pg
import pywinauto
import numpy as np
from pywinauto.keyboard import send_keys
from email.mime.text import MIMEText
from PIL import Image, ImageEnhance
import pytesseract
from selenium.webdriver import ActionChains
from selenium.webdriver.support import expected_conditions as EC


class TikTok_de():
    # 需要的参数
    def __init__(self, Sender_Add, ZhenHe_User, ZhenHe_Pwd, Colour_Browser):
        self.Sender_Add = Sender_Add
        self.ZhenHe_User = ZhenHe_User
        self.ZhenHe_Pwd = ZhenHe_Pwd
        self.Colour_Browser = Colour_Browser

    # ======下面是邮件======
    def Runfailed(self):
        # 设置邮箱所需的服务器信息和账号等信息
        Send_Add = self.Sender_Add
        Email_UserName = ""
        Email_pwd = ""
        Sender_Add = ""
        # “发送给”可以有多个人，所以用数组
        recipients = [""]
        recipients = np.array(recipients)
        # 设置邮箱信息
        # 设置邮箱消息内容
        information = MIMEText('抖音数据拉取失败，请及时查看脚本执行情况，具体原因请查看Pycharm输出的错误信息，谢谢~', 'plain', 'UTF-8')
        # 邮件标题
        information['Subject'] = '抖音数据获取程序出错，请及时查看，谢谢~'
        # 发件人信息
        information['From'] = Sender_Add
        # 接收方信息
        information['To'] = recipients[0]
        # 使用这些信息登录，并发送邮件
        try:
            connection_sever = smtplib.SMTP()
            # 连接到服务器
            connection_sever.connect(Send_Add, 25)
            # 登录到服务器
            connection_sever.login(Email_UserName, Email_pwd)
            # 发送邮件
            connection_sever.sendmail(Sender_Add, recipients, information.as_string())
            # 退出连接服务器
            connection_sever.quit()
            print("运行报错,邮件发送成功~")
        except Exception as e:
            print(e)

    # ======上面是邮件代码======

    # 超级供应链店铺数据拉取
    def SSC(self):
        try:
            wb = webdriver.Chrome()
            wb.implicitly_wait(5)
            wb.get("https://fxg.jinritemai.com/")
            wb.maximize_window()
            wb.find_element_by_class_name("ant-dropdown-trigger").click()
            time.sleep(1)
            wb.find_element_by_xpath(
                "//div[contains(@class,'account-center-switch-button switch-switch email false')]").click()
            time.sleep(1)
            # 输入账号和密码
            wb.find_element_by_name("email").send_keys("")
            wb.find_element_by_name("password").send_keys("")
            wb.find_element_by_class_name("account-center-action-button").click()
            time.sleep(4)
            # 点击营销中心
            Market_Center = wb.find_elements_by_css_selector("div._3uAZMbdh8bDlHUQMv7dO-8 ._1YfWztp2KLYkBljnVsw-b8")[0]
            Market_Center.click()
            all_window = wb.window_handles
            time.sleep(3)
            # 跳转到第二个窗口
            wb.switch_to.window(all_window[1])
            # 营销中心的“引导”下一步,连续来三次
            wb.find_element_by_xpath("//button[contains(@class,'ant-btn ant-btn-primary')]").click()
            time.sleep(1)
            wb.find_element_by_xpath("//button[contains(@class,'ant-btn ant-btn-primary')]").click()
            time.sleep(1)
            wb.find_element_by_xpath("//button[contains(@class,'ant-btn ant-btn-primary')]").click()
            time.sleep(2)
            # 点击联盟数据
            League_Data = wb.find_elements_by_class_name("index-menuContainer--JZWR_")
            League_Data[18].click()
            # 跳转到第三个窗口
            time.sleep(2)
            all_window1 = wb.window_handles
            wb.switch_to.window(all_window1[2])
            time.sleep(2)
            for the_next in range(3):
                wb.find_element_by_xpath(
                    "//button[contains(@class,'ant-btn guides__customFooter__btn ant-btn-primary')]").click()
                time.sleep(1)
            time.sleep(1)
            # 点击联盟订单明细
            wb.find_element_by_class_name("menu_order").click()
            time.sleep(2)
            # 点击导出
            wb.find_element_by_xpath(
                "//button[contains(@class,'ant-btn data-order-export__btn _3fazBonqKXIqs12FLs6KqI')]").click()
            # 弹框的导出
            time.sleep(3)
            Popout_dc = wb.find_element_by_css_selector("div.ant-modal-confirm-btns .ant-btn-primary")
            wb.execute_script("arguments[0].click();", Popout_dc)
            # 等待报表完成
            time.sleep(30)
            pg.press("F5")
            time.sleep(2)
            # 点击下载报表
            download_bb = wb.find_elements_by_class_name("ant-btn-dashed")[0]
            download_bb.click()
            self.Open_xyou()
            time.sleep(3)
            self.Colourful_seasons()
        except Exception as e:
            self.Runfailed()
            print(e)
            wb.quit()
        wb.quit()

    def Open_xyou(self):
        wb = webdriver.Chrome()
        wb.maximize_window()
        try:
            wb.get("http://erp.xyooou.com")
            #####以下是验证码#####
            # 截取屏幕内容，保存到本地
            time.sleep(2)
            wb.save_screenshot(r"D:\Tik_Tok_image\01.png")
            # 3、打开截图，获取验证码位置，截取保存验证码
            ran = Image.open(r"D:\Tik_Tok_image\01.png")
            box = (1352, 520, 1429, 553)  # 获取验证码位置,自动定位不是很明白，就使用了手动定位，代表（左，上，右，下）
            ran.crop(box).save(r"D:\Tik_Tok_image\02.png")
            # 获取验证码图片，读取验证码
            imageCode = Image.open(r"D:\Tik_Tok_image\02.png")  # 图像增强，二值化
            # imageCode.load()
            time.sleep(1)
            sharp_img = ImageEnhance.Contrast(imageCode).enhance(2.0)
            sharp_img.save(r"D:\Tik_Tok_image\03.png")
            sharp_img.load()  # 对比度增强
            global code
            time.sleep(2)
            code = pytesseract.image_to_string(sharp_img).strip()
            # 收到验证码，进行输入验证
            print(code)
            #####以上是验证码#####
            # 输入账号密码
            wb.find_element_by_id("txtUser").send_keys("")
            wb.find_element_by_id("txtPass").send_keys("")
            time.sleep(2)
            wb.find_element_by_id("txt_code").send_keys(code)
            time.sleep(2)
            # 登录
            wb.find_element_by_id("login_button").click()
            time.sleep(2)
            alert_is_T = EC.alert_is_present()(wb)
            if alert_is_T:
                print(alert_is_T.text)
                alert_is_T.accept()
                self.Open_xyou()
            else:
                # 选择管理员
                wb.find_elements_by_class_name("btn-primary")[0].click()
                # 点击旺店通管理
                wb.find_elements_by_css_selector(".nav-label")[12].click()
                # 点击精选联盟订单
                time.sleep(2)
                wb.find_elements_by_css_selector("ul.in .J_menuItem")[3].click()
                # 进入精选联盟的iframe
                time.sleep(2)
                wb.switch_to.frame("iframe4")
                time.sleep(2)
                Feil_Button = wb.find_element_by_id("DefaultContent_fuTmp")
                ActionChains(wb).click(Feil_Button).perform()
                time.sleep(2)
                # 操作文件选择框
                Pwa = pywinauto.Desktop()
                # 锁定打开的文件上传窗口
                File_Window = Pwa["打开"]
                time.sleep(2)
                # 下方是文件地址框输入
                File_Window["Toolbar3"].click()
                time.sleep(2)
                # 输入路径
                send_keys("下载")
                time.sleep(2)
                # 输入回车键
                send_keys("{VK_RETURN}")
                time.sleep(2)
                #    选中文件名输入框，输入文件名
                pg.moveTo(368, 180)
                pg.doubleClick()
                time.sleep(4)
                wb.find_element_by_id("DefaultContent_btnImport").click()
                time.sleep(10)
                alertisTrue = wb.switch_to.alert
                if alertisTrue:
                    print(alertisTrue.text)
                    alertisTrue.accept()
                    wb.quit()
                elif alertisTrue.text == "导入失败":
                    self.Runfailed()
        except NoSuchElementException as NSE:
            print(NSE)
            self.Runfailed()
            wb.quit()
        except NoAlertPresentException as NAPE:
            print(NAPE)
            wb.quit()

        # 四季缤纷环球优选

    def Colourful_seasons(self):
        try:
            wb = webdriver.Chrome()
            wb.implicitly_wait(5)
            wb.get(self.Colour_Browser)
            wb.maximize_window()
            wb.find_element_by_class_name("ant-dropdown-trigger").click()
            time.sleep(2)
            wb.find_element_by_xpath(
                "//div[contains(@class,'account-center-switch-button switch-switch email false')]").click()
            time.sleep(1)
            # 输入账号和密码
            wb.find_element_by_name("email").send_keys(self.ZhenHe_User)
            wb.find_element_by_name("password").send_keys(self.ZhenHe_Pwd)
            wb.find_element_by_class_name("account-center-action-button").click()
            time.sleep(4)
            # 自行解决图片滑块验证码，直接用滑动滑块这种较为简单的方式
            Loosen_location = 920
            for cs in range(15):
                pg.mouseDown(820, 683)
                pg.moveTo(Loosen_location, 683, duration=2)
                pg.mouseUp(Loosen_location, 683)
                Loosen_location += 9
                time.sleep(3)
            # ======以上是滑块验证码======
            # 获取四季缤纷店铺进入按钮
            Colourful_Enter = wb.find_elements_by_class_name("_4MKt8VAcdcbsw_P2wgbVx")

            time.sleep(2)
            Colourful_Enter[0].click()
            time.sleep(3)
            # 关闭广告
            gg = wb.find_element_by_xpath(
                "//span[contains(@class,'anticon anticon-close-circle _326C__nFPKLjTbzS8wQYuc')]")
            if gg:
                gg.click()
            time.sleep(2)
            for now in range(5):
                I_Know = wb.find_element_by_xpath("//button[contains(@class,'ant-btn ant-btn-primary')]")
                I_Know.click()
                time.sleep(2)
            time.sleep(3)
            # wb.find_element_by_class_name("ant-btn-primary").click()
            # 进入营销中心
            Market_Center = wb.find_elements_by_css_selector("div._3uAZMbdh8bDlHUQMv7dO-8 ._1YfWztp2KLYkBljnVsw-b8")[0]
            time.sleep(1)
            Market_Center.click()
            time.sleep(1)
            all_window = wb.window_handles
            time.sleep(2)
            # 跳转到第二个窗口
            wb.switch_to.window(all_window[1])
            # 点击“下一步”
            for Next in range(3):
                The_Next = wb.find_element_by_xpath("//button[contains(@class,'ant-btn ant-btn-primary')]")
                The_Next.click()
                time.sleep(1)
            # 点击联盟数据
            League_Data = wb.find_elements_by_class_name("index-menuContainer--JZWR_")
            League_Data[17].click()
            time.sleep(1)
            all_window1 = wb.window_handles
            # 跳转到第三个窗口
            wb.switch_to.window(all_window1[2])
            time.sleep(2)
            for the_next in range(3):
                wb.find_element_by_xpath(
                    "//button[contains(@class,'ant-btn guides__customFooter__btn ant-btn-primary')]").click()
                time.sleep(1)
            time.sleep(1)
            # 点击联盟订单明细
            wb.find_element_by_class_name("menu_order").click()
            time.sleep(2)
            wb.find_element_by_xpath(
                "//button[contains(@class,'ant-btn data-order-export__btn _3fazBonqKXIqs12FLs6KqI')]").click()
            # 弹框的导出
            time.sleep(2)
            Popout_dc = wb.find_element_by_css_selector("div.ant-modal-confirm-btns .ant-btn-primary")
            wb.execute_script("arguments[0].click();", Popout_dc)
            # 等待报表完成
            time.sleep(30)
            pg.press("F5")
            time.sleep(2)
            # 点击下载报表
            download_bb = wb.find_elements_by_class_name("ant-btn-dashed")[0]
            download_bb.click()
            # 执行小柚，把数据导入
            self.Open_xyou()
            time.sleep(2)
        except NoSuchElementException as NSEE:
            self.Colourful_seasons()
        except Exception as e:
            print(e)
            self.Runfailed()
            wb.quit()
        # 执行小柚，把数据导入
        time.sleep(10)
        wb.quit()
        self.Zhenhe()

    # 臻和科技
    def Zhenhe(self):
        try:
            wb = webdriver.Chrome()
            wb.implicitly_wait(5)
            wb.get(self.Colour_Browser)
            wb.maximize_window()
            wb.find_element_by_class_name("ant-dropdown-trigger").click()
            time.sleep(2)
            wb.find_element_by_xpath(
                "//div[contains(@class,'account-center-switch-button switch-switch email false')]").click()
            time.sleep(1)
            # 输入账号和密码
            wb.find_element_by_name("email").send_keys(self.ZhenHe_User)
            wb.find_element_by_name("password").send_keys(self.ZhenHe_Pwd)
            wb.find_element_by_class_name("account-center-action-button").click()
            time.sleep(4)
            # 自行解决图片滑块验证码，直接用滑动滑块这种较为简单的方式
            Loosen_location = 920
            for cs in range(15):
                pg.mouseDown(820, 683)
                pg.moveTo(Loosen_location, 683, duration=2)
                pg.mouseUp(Loosen_location, 683)
                Loosen_location += 9
                time.sleep(3)
            # ======以上是滑块验证码======
            # 选择“臻和科技”店铺
            Colourful_Enter = wb.find_elements_by_class_name("_4MKt8VAcdcbsw_P2wgbVx")
            if Colourful_Enter:
                Colourful_Enter[1].click()
                time.sleep(2)
                # 关闭广告
                gg = wb.find_element_by_xpath(
                    "//span[contains(@class,'anticon anticon-close-circle _326C__nFPKLjTbzS8wQYuc')]")
                if gg:
                    gg.click()
                time.sleep(2)
                # 下载浏览器的弹窗
                download_borwser = wb.find_element_by_xpath(
                    "//img[contains(@src,'//sf3-ecomcdn-tos.pstatp.com/obj/ecom-luban-cdn/shopfxg3/images/2_a1OF4.png')]")
                if download_borwser:
                    download_borwser.click()
                time.sleep(2)
                for now in range(5):
                    I_Know = wb.find_element_by_xpath("//button[contains(@class,'ant-btn ant-btn-primary')]")
                    I_Know.click()
                    time.sleep(2)
                time.sleep(3)
                # 进入营销中心
                Market_Center = \
                wb.find_elements_by_css_selector("div._3uAZMbdh8bDlHUQMv7dO-8 ._1YfWztp2KLYkBljnVsw-b8")[0]
                Market_Center.click()
                time.sleep(2)
                all_window = wb.window_handles
                # 跳转到第二个窗口
                wb.switch_to.window(all_window[1])
                time.sleep(2)
                # 点击“下一步”
                for Next in range(3):
                    The_Next = wb.find_element_by_xpath("//button[contains(@class,'ant-btn ant-btn-primary')]")
                    The_Next.click()
                    time.sleep(1)
                # 点击联盟数据
                League_Data = wb.find_elements_by_class_name("index-menuContainer--JZWR_")[18]
                League_Data.click()
                time.sleep(2)
                all_window1 = wb.window_handles
                # 跳转到第三个窗口
                wb.switch_to.window(all_window1[2])
                time.sleep(2)
                for the_next in range(3):
                    wb.find_element_by_xpath(
                        "//button[contains(@class,'ant-btn guides__customFooter__btn ant-btn-primary')]").click()
                    time.sleep(1)
                time.sleep(1)
                # 点击联盟订单明细
                wb.find_element_by_class_name("menu_order").click()
                time.sleep(2)
                wb.find_element_by_xpath(
                    "//button[contains(@class,'ant-btn data-order-export__btn _3fazBonqKXIqs12FLs6KqI')]").click()
                # 弹框的导出
                time.sleep(2)
                Popout_dc = wb.find_element_by_css_selector("div.ant-modal-confirm-btns .ant-btn-primary")
                wb.execute_script("arguments[0].click();", Popout_dc)
                # 等待报表完成
                time.sleep(30)
                pg.press("F5")
                time.sleep(2)
                # 点击下载报表
                download_bb = wb.find_elements_by_class_name("ant-btn-dashed")[0]
                download_bb.click()
                time.sleep(1)
                self.Open_xyou()
            else:
                wb.quit()
                self.Zhenhe()
        except Exception as e:
            print(e)
            time.sleep(50)
            self.Runfailed()
            wb.quit()
            # 执行小柚，把数据导入
        time.sleep(10)
        wb.quit()


while True:
    time.sleep(1)
    TikTok_de(Sender_Add="smtp.ym.163.com", ZhenHe_User="", ZhenHe_Pwd="",
              Colour_Browser="https://fxg.jinritemai.com/").Colourful_seasons()
    time.sleep(1700)
